package br.inf.mensageiro.tree;

import java.io.IOException;
import java.util.Map;

import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

import br.inf.mensageiro.context.ApplicationContext;
import br.inf.mensageiro.multicast.ServerMulticast;
import br.inf.mensageiro.pojo.Status;
import br.inf.mensageiro.pojo.Usuario;

public class TreeNodeDecision {

	public static void node(JTree mainTree, DefaultTreeModel treeModel, DefaultMutableTreeNode top, Usuario usuario) throws IOException {
		ApplicationContext applicationContext = ApplicationContext.getInstance();
		Map<String, CustomMutableTreeNode> nodeMap = applicationContext.getNodeMap();
		if (usuario.getStatus() == Status.ON_LINE && !applicationContext.getNodeMap().containsKey(usuario.getIpRemote())) {
			ServerMulticast.send(Status.ON_LINE);
			if (!nodeMap.containsKey(usuario.getIpRemote())) {
				int existingNodes = top.getChildCount();
				CustomMutableTreeNode userNode = new CustomMutableTreeNode(usuario);
				applicationContext.getHosts().put(usuario.getUserName(), usuario.getIpRemote());
				nodeMap.put(usuario.getIpRemote(), userNode);
				top.add(userNode);
				mainTree.expandRow(0);
				int index[] = { existingNodes };
				treeModel.nodesWereInserted(top, index);
			}
		}

		if (usuario.getStatus() == Status.OFF_LINE) {
			DefaultMutableTreeNode node = nodeMap.get(usuario.getIpRemote());
			if (node != null) {
				int index = top.getIndex(node);
				int indexArr[] = { index };
				top.remove(node);
				Object removedChildren[] = { node };
				treeModel.nodesWereRemoved(top, indexArr, removedChildren);
				nodeMap.remove(usuario.getIpRemote());
			}
		}
	}
}
